const weapi = require('./apis/index.js')
const wesrv = require('./apis/service.js')

var util = require('./utils/util.js');
var api = require('./config/api.js');
var user = require('./utils/user.js');

App({
  onLaunch: function() {
    Promise.prototype.finally = function(callback){
      let P = this.constructor;
      return this.then(
              value => {
                   P.resolve(callback()).then(() => value)
               },
               reason => {
                   P.resolve(callback()).then(() => { throw reason })
               }
           )
    }
    const updateManager = wx.getUpdateManager();
    wx.getUpdateManager().onUpdateReady(function() {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: function(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    this.doTmpLogin()
    // // 尝试更新token
    // wesrv.tryUpdateToken().then(() => {
    //   console.log('尝试更新token 1')
    // }, () => {
    //   console.log('尝试更新token 2')
    // })
  },
  onShow: function(options) {
    user.checkLogin().then(res => {
      this.globalData.hasLogin = true;
    }).catch(() => {
      this.globalData.hasLogin = false;
    });
  },
  globalData: {
    hasNewMessage: false,
    hasLogin: false,
    userInfo: null
    
  },
   setHasNewMessage: function (value) {
    this.globalData.hasNewMessage = value;
  
  },

  isLogin() {
    console.log('检查登录')
    return new Promise((resolve, reject) => {
      var token = wx.getStorageSync('token')
      if (!token) {
        wx.clearStorage()
        reject()
        return
      }
      var mode  = wx.getStorageSync('tokenmode')
      var time  = wx.getStorageSync('tokentime')
      var d1 = 1000 * 60 * 60 * 24
      if (Date.now() > (time + d1) || Date.now() > (time + (d1 / 2))) {
        // 已过期
        // 未过期，进行token更新
        reject()
      } else {
        // 正在有效期内
        // 回调
        resolve()
      }
    })
  },

  checkLogin() {
    console.log('检查登录')
    return new Promise((resolve, reject) => {
      var token = wx.getStorageSync('token')
      if (!token) {
        wx.clearStorage()
        wx.navigateTo({
          url: '/pages/login/tmplogin',
        })
        reject()
        return
      }
      var mode  = wx.getStorageSync('tokenmode')
      var time  = wx.getStorageSync('tokentime')
      var timeNumber = parseInt(time)
      var d1 = 1000 * 60 * 60 * 24
      var d2 = Date.now()
      var dt = d2 - d2 % d1
      if (timeNumber < dt) {
        // 已过期
        // 未过期，进行token更新
        wx.navigateTo({
          url: '/pages/login/tmplogin',
        })
        reject()
      } else {
        // 正在有效期内
        // 回调
        resolve()
      }
    })
  },
  // 临时登录
  doTmpLogin() {
    var that = this
    // wx.showLoading({
    //   title: '正在登录',
    // })
    var username = 'weixinapply'
    var password = '12345678'
    weapi.tmplogin(username, password).then(res => {
      console.log('res', res)
      var token = res.data
      if (token) {
        wx.setStorageSync('token', token)
        wx.setStorageSync('tokenmode', 'username_and_password')
        wx.setStorageSync('tokentime', Date.now())
        wx.setStorageSync('login_username', username)
        wx.setStorageSync('login_password', password)
      } else {
        // wx.hideLoading()
        // wx.showModal({
        //   title: '提示',
        //   content: res.message
        // })
      }
    }, () => {
      // wx.hideLoading()
      // wx.showModal({
      //   title: '提示',
      //   content: '登录失败'
      // })
    })
  },
})